<template>
  <view class="exhibition-form">
    <!-- 基本信息表单 -->
    <view class="form-section">
      <view class="form-group">
        <text class="label">展览名称</text>
        <input 
          class="input" 
          v-model="formData.title" 
          placeholder="请输入展览名称"
          maxlength="50"
        />
      </view>

      <view class="form-group">
        <text class="label">美术馆名称</text>
        <input 
          class="input" 
          v-model="formData.museum" 
          placeholder="请输入美术馆名称"
          maxlength="50"
        />
      </view>

      <view class="form-group">
        <text class="label">城市</text>
        <input 
          class="input" 
          v-model="formData.city" 
          placeholder="请输入城市"
          maxlength="30"
        />
      </view>

      <view class="form-group">
        <text class="label">国家</text>
        <input 
          class="input" 
          v-model="formData.country" 
          placeholder="请输入国家"
          maxlength="30"
        />
      </view>

      <view class="form-group">
        <text class="label">日期</text>
        <picker 
          mode="date" 
          :value="formData.date" 
          @change="onDateChange"
          class="date-picker"
        >
          <view class="picker-display">
            <text>{{ formData.date || '请选择日期' }}</text>
            <text class="picker-arrow">▼</text>
          </view>
        </picker>
      </view>

      <view class="form-group">
        <text class="label">AI总体解读</text>
        <textarea 
          class="textarea" 
          v-model="formData.aiSummary" 
          placeholder="AI将为您生成展览的总体解读..."
          maxlength="500"
          :disabled="isGeneratingAI"
        />
        <button 
          class="ai-generate-btn" 
          @click="generateAISummary"
          :disabled="isGeneratingAI"
        >
          {{ isGeneratingAI ? '生成中...' : 'AI生成解读' }}
        </button>
      </view>
    </view>

    <!-- 媒体管理标签页 -->
    <!-- <view class="tab-section" v-if="!$props.hideMedia">
      <view class="tab-bar">
        <button 
          class="tab-btn" 
          :class="{ active: activeTab === 'exhibit' }" 
          @click="switchTab('exhibit')"
        >
          展览照片
        </button>
        <button 
          class="tab-btn" 
          :class="{ active: activeTab === 'aigc' }" 
          @click="switchTab('aigc')"
        >
          AIGC照片和视频
        </button>
      </view -->>

      <!-- 展览照片标签页 -->
     <!-- <view v-if="activeTab === 'exhibit'" class="media-container">
        <view class="media-header">
          <text class="media-title">展览照片</text>
          <button class="add-media-btn" @click="addExhibitionPhoto">
            <text class="add-icon">+</text>
            <text>添加照片</text>
          </button>
        </view>

        <view class="media-grid">
          <view 
            v-for="(photo, index) in sortedExhibitPhotos" 
            :key="photo.id"
            class="media-item"
            :class="{ pinned: photo.pinned }"
          >
            <image :src="photo.url" mode="aspectFill" class="media-image" />
            <view class="media-overlay">
              <button 
                class="pin-btn" 
                @click="togglePin(photo, 'exhibit')"
                :class="{ active: photo.pinned }"
              >
                📌
              </button>
              <button class="delete-btn" @click="deletePhoto(photo, 'exhibit')">
                🗑️
              </button>
            </view>
          </view>
        </view>
      </view>

      <!-- AIGC照片和视频标签页（已移除） -->
      <!-- </view> -->

  </view>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'

// Props
const props = defineProps({
  initialData: {
    type: Object,
    default: () => ({})
  },
  hideMedia: {
    type: Boolean,
    default: false
  }
})

// Emits
const emit = defineEmits(['save', 'update:formData'])

// 表单数据
const formData = reactive({
  title: '',
  museum: '',
  city: '',
  country: '',
  date: '',
  aiSummary: '',
  ...props.initialData
})

// 媒体数据
const exhibitPhotos = ref([])
const aigcMedia = ref([])

// 状态管理
const activeTab = ref('exhibit')
const isGeneratingAI = ref(false)
const isGeneratingAIGC = ref(false)
const isMultiSelectMode = ref(false)
const selectedPhotos = ref([])

// 计算属性：排序后的媒体（置顶的在前）
const sortedExhibitPhotos = computed(() => {
  return [...exhibitPhotos.value].sort((a, b) => {
    if (a.pinned && !b.pinned) return -1
    if (!a.pinned && b.pinned) return 1
    return 0
  })
})

const sortedAIGCMedia = computed(() => {
  return [...aigcMedia.value].sort((a, b) => {
    if (a.pinned && !b.pinned) return -1
    if (!a.pinned && b.pinned) return 1
    return 0
  })
})

// 初始化媒体数据（默认不注入任何预设图，避免误当封面）
function initMediaData() {
  exhibitPhotos.value = []
  aigcMedia.value = []
}

// 日期选择
function onDateChange(e) {
  formData.date = e.detail.value
}

// 切换标签页
function switchTab(tab) {
  activeTab.value = tab
}

// 添加展览照片
function addExhibitionPhoto() {
  uni.chooseImage({
    count: 9,
    success: (res) => {
      const newPhotos = res.tempFilePaths.map((path, index) => ({
        id: Date.now() + index,
        url: path,
        pinned: false,
        userAdded: true
      }))
      exhibitPhotos.value.push(...newPhotos)
      uni.showToast({ title: `添加了${newPhotos.length}张照片`, icon: 'success' })
    },
    fail: (err) => {
      console.error('选择照片失败:', err)
      uni.showToast({ title: '选择照片失败', icon: 'error' })
    }
  })
}

// 添加AIGC媒体
function addAIGCMedia() {
  uni.chooseMedia({
    count: 9,
    mediaType: ['image', 'video'],
    success: (res) => {
      const newMedia = res.tempFiles.map((file, index) => ({
        id: Date.now() + index,
        type: file.fileType.startsWith('image') ? 'image' : 'video',
        url: file.tempFilePath,
        coverUrl: file.thumbTempFilePath,
        pinned: false
      }))
      aigcMedia.value.push(...newMedia)
      uni.showToast({ title: `添加了${newMedia.length}个媒体`, icon: 'success' })
    },
    fail: (err) => {
      console.error('选择媒体失败:', err)
      uni.showToast({ title: '选择媒体失败', icon: 'error' })
    }
  })
}

// 切换置顶状态
function togglePin(item, type) {
  item.pinned = !item.pinned
  uni.showToast({ 
    title: item.pinned ? '已置顶' : '已取消置顶', 
    icon: 'success' 
  })
}

// 删除照片
function deletePhoto(photo, type) {
  uni.showModal({
    title: '确认删除',
    content: '确定要删除这张照片吗？',
    success: (res) => {
      if (res.confirm) {
        if (type === 'exhibit') {
          const index = exhibitPhotos.value.findIndex(p => p.id === photo.id)
          if (index > -1) {
            exhibitPhotos.value.splice(index, 1)
          }
        }
        uni.showToast({ title: '已删除', icon: 'success' })
      }
    }
  })
}

// 删除媒体
function deleteMedia(media, type) {
  uni.showModal({
    title: '确认删除',
    content: '确定要删除这个媒体吗？',
    success: (res) => {
      if (res.confirm) {
        if (type === 'aigc') {
          const index = aigcMedia.value.findIndex(m => m.id === media.id)
          if (index > -1) {
            aigcMedia.value.splice(index, 1)
          }
        }
        uni.showToast({ title: '已删除', icon: 'success' })
      }
    }
  })
}

// 播放视频
function playVideo(url) {
  uni.navigateTo({
    url: `/pages/video-player/video-player?videoUrl=${encodeURIComponent(url)}`
  })
}

// AI生成解读
function generateAISummary() {
  isGeneratingAI.value = true
  
  // 模拟AI生成过程
  setTimeout(() => {
    formData.aiSummary = `这是一场关于${formData.title || '艺术'}的精彩展览，展现了${formData.museum || '美术馆'}的独特魅力。展览通过精心策划的展品，为观众呈现了丰富的艺术体验和文化内涵。`
    isGeneratingAI.value = false
    uni.showToast({ title: 'AI解读生成完成', icon: 'success' })
  }, 2000)
}

// 切换多选模式
function toggleMultiSelect() {
  isMultiSelectMode.value = !isMultiSelectMode.value
  selectedPhotos.value = []
}

// 全选照片
function selectAllPhotos() {
  selectedPhotos.value = exhibitPhotos.value.map(photo => photo.id)
  uni.showToast({ title: `已选择${selectedPhotos.value.length}张照片`, icon: 'success' })
}

// 从选中照片生成AIGC
function generateAIGCFromSelected() {
  if (selectedPhotos.value.length === 0) {
    uni.showToast({ title: '请先选择照片', icon: 'none' })
    return
  }
  
  isGeneratingAIGC.value = true
  
  // 模拟AIGC生成过程
  setTimeout(() => {
    const newAIGCMedia = selectedPhotos.value.map((photoId, index) => ({
      id: Date.now() + index,
      type: Math.random() > 0.5 ? 'image' : 'video',
      url: `/static/aigc_${index + 1}.png`,
      coverUrl: `/static/aigc_cover_${index + 1}.png`,
      pinned: false
    }))
    
    aigcMedia.value.push(...newAIGCMedia)
    selectedPhotos.value = []
    isMultiSelectMode.value = false
    isGeneratingAIGC.value = false
    
    uni.showToast({ 
      title: `生成了${newAIGCMedia.length}个AIGC作品`, 
      icon: 'success' 
    })
  }, 3000)
}

// 获取表单数据
function getFormData() {
  return {
    ...formData,
    exhibitPhotos: exhibitPhotos.value,
    aigcMedia: aigcMedia.value
  }
}

// 验证表单
function validateForm() {
  if (!formData.title.trim()) {
    uni.showToast({ title: '请输入展览名称', icon: 'none' })
    return false
  }
  
  if (!formData.museum.trim()) {
    uni.showToast({ title: '请输入美术馆名称', icon: 'none' })
    return false
  }
  
  if (!formData.date) {
    uni.showToast({ title: '请选择日期', icon: 'none' })
    return false
  }
  
  return true
}

// 暴露方法给父组件
defineExpose({
  getFormData,
  validateForm
})

// 初始化
initMediaData()
</script>

<style lang="scss" scoped>
.exhibition-form {
  .form-section {
    background: #333333;
    border-radius: 16px;
    padding: 20px;
    margin-bottom: 20px;
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.3);
    border: 1px solid #444444;
  }

  .form-group {
    margin-bottom: 20px;
    
    .label {
      display: block;
      color: #ffffff;
      font-size: 14px;
      font-weight: 600;
      margin-bottom: 16rpx;
      font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
    }
    
    .input {
      width: 100%;
      height: 96rpx;
      padding: 0 32rpx;
      border: 2rpx solid #444444;
      border-radius: 24rpx;
      background: #2a2a2a;
      color: #ffffff;
      font-size: 14px;
      line-height: 96rpx;
      box-sizing: border-box;
      transition: border-color 0.2s ease;
      display: flex;
      align-items: center;
      
      &:focus {
        border-color: #ff0050;
        outline: none;
      }
      
      &::placeholder {
        color: #999999;
        opacity: 1;
      }
    }
    
    .textarea {
      width: 100%;
      min-height: 160rpx;
      padding: 24rpx 32rpx;
      border: 2rpx solid #444444;
      border-radius: 24rpx;
      background: #2a2a2a;
      color: #ffffff;
      font-size: 14px;
      line-height: 1.5;
      resize: none;
      box-sizing: border-box;
      transition: border-color 0.2s ease;
      vertical-align: top;
      
      &:focus {
        border-color: #ff0050;
        outline: none;
      }
      
      &::placeholder {
        color: #999999;
        opacity: 1;
      }
    }
    
    .date-picker {
      width: 100%;
      
      .picker-display {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 14px 16px;
        border: 1px solid rgba(212, 175, 55, 0.2);
        border-radius: 12px;
        background: #2a2a2a;
        color: #ffffff;
        font-size: 14px;
        line-height: 1.4;
        transition: border-color 0.2s ease;
        
        &:active {
          border-color: #ff0050;
        }
        
        .picker-arrow {
          color: #d4af37;
          font-size: 12px;
        }
      }
    }
    
    .ai-generate-btn {
      margin-top: 8px;
      background: linear-gradient(135deg, #ff0050, #ff4081);
      color: #ffffff;
      border: none;
      border-radius: 20px;
      padding: 8px 16px;
      font-size: 12px;
      font-weight: 600;
      
      &:disabled {
        opacity: 0.6;
      }
    }
  }

  .tab-section {
    background: #333333;
    border-radius: 16px;
    padding: 20px;
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.3);
    border: 1px solid #444444;
  }

  .tab-bar {
    display: flex;
    width: 100%;
    margin-bottom: 20px;
    background: #444444;
    border-radius: 25px;
    padding: 4px;
  }

  .tab-btn {
    flex: 1;
    background: none;
    border: none;
    padding: 12px 0;
    font-size: 14px;
    color: #ffffff;
    border-radius: 20px;
    font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
    font-weight: 300;
    
    &.active {
      color: #ffffff;
      background: linear-gradient(135deg, #ff0050, #ff4081);
      font-weight: 400;
      box-shadow: 0 4px 12px rgba(212, 175, 55, 0.3);
    }
  }

  .media-container {
    margin-bottom: 20px;
  }

  .media-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    
    .media-title {
      font-size: 16px;
      font-weight: 600;
      color: #ffffff;
      font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
    }
    
    .add-media-btn {
      display: flex;
      align-items: center;
      background: linear-gradient(135deg, #ff0050, #ff4081);
      color: #ffffff;
      border: none;
      border-radius: 20px;
      padding: 6px 6px;
      font-size: 12px;
      font-weight: 600;
      left: 30px;
      .add-icon {
        margin-right: 4px;
        font-size: 14px;
      }
    }
  }

  .media-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 12px;
  }

  .media-item {
    position: relative;
    aspect-ratio: 1;
    border-radius: 12px;
    overflow: hidden;
    background: linear-gradient(135deg, rgba(255,255,255,0.9), rgba(245,242,237,0.9));
    box-shadow: 0 4px 12px rgba(212, 175, 55, 0.15);
    
    &.pinned {
      border: 2px solid #d4af37;
    }
    
    .media-image {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
    
    .video-item {
      position: relative;
      width: 100%;
      height: 100%;
      
      .play-overlay {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        width: 40px;
        height: 40px;
        background: rgba(0, 0, 0, 0.6);
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        
        .play-icon {
          color: white;
          font-size: 16px;
          font-weight: bold;
        }
      }
    }
    
    .media-overlay {
      position: absolute;
      top: 4px;
      right: 4px;
      display: flex;
      gap: 4px;
      
      .pin-btn, .delete-btn {
        width: 24px;
        height: 24px;
        border-radius: 50%;
        border: none;
        font-size: 12px;
        display: flex;
        align-items: center;
        justify-content: center;
        backdrop-filter: blur(4px);
        
        &.pin-btn {
          background: rgba(255, 255, 255, 0.8);
          
          &.active {
            background: rgba(212, 175, 55, 0.8);
          }
        }
        
        &.delete-btn {
          background: rgba(255, 0, 0, 0.8);
        }
      }
    }
  }

  .aigc-generate-section {
    margin-top: 20px;
    padding-top: 20px;
    border-top: 1px solid rgba(212, 175, 55, 0.2);
    
    .multi-select-btn {
      width: 100%;
      background: linear-gradient(135deg, #ff0050, #ff4081);
      color: #ffffff;
      border: none;
      border-radius: 20px;
      padding: 12px 20px;
      font-size: 14px;
      font-weight: 600;
      margin-bottom: 12px;
      
      &.active {
        background: linear-gradient(135deg, #8b4513, #5d4e37);
        color: #ffffff;
      }
    }
    
    .multi-select-controls {
      display: flex;
      gap: 12px;
      
      .select-all-btn, .generate-aigc-btn {
        flex: 1;
        background: rgba(212, 175, 55, 0.2);
        color: #ffffff;
        border: none;
        border-radius: 16px;
        padding: 10px 16px;
        font-size: 12px;
        font-weight: 600;
        
        &:disabled {
          opacity: 0.6;
        }
      }
      
      .generate-aigc-btn {
        background: linear-gradient(135deg, #ff0050, #ff4081);
      }
    }
  }
}

/* 屏幕适配媒体查询 */
@media screen and (max-width: 375px) {
  .exhibition-form {
    .form-section {
      padding: 30rpx;
    }
    
    .input {
      height: 88rpx;
      font-size: 13px;
      line-height: 88rpx;
    }
    
    .textarea {
      min-height: 140rpx;
      font-size: 13px;
    }
  }
}

@media screen and (min-width: 414px) {
  .exhibition-form {
    .form-section {
      padding: 50rpx;
    }
    
    .input {
      height: 104rpx;
      font-size: 15px;
      line-height: 104rpx;
    }
    
    .textarea {
      min-height: 180rpx;
      font-size: 15px;
    }
  }
}
</style>
